import React, { useEffect, useState } from 'react'
import axios from "axios"
import "./Duanzi.css"
export default function Duanzi() {

    //声明段子状态
    let [duanzi,setDuanzi] = useState([]);

    //声明模态框状态
    let [model,setModel] = useState(false);

    // 某个段子的状态
    let [one,setOne] = useState({});

    useEffect(()=>{ 
        axios.get("http://api.xiaohigh.com/duanzi").then(response=>{
            // Promise 对象的成功的结果值
            // console.log(response.data);
            //更新状态
            setDuanzi(response.data);

        },error=>{
            console.log(error.message);
        })
       
    },[])


    //创建展示模态框及遮罩层 及 数据方法
    let showModel = (value)=>{
       return ()=>{
            //展示模态框及遮罩层
            setModel(true);
            //设置某个段子
            setOne(value);
       }
    }

    //关闭模态框
    let hide = ()=>{
         //展示模态框及遮罩层
         setModel(false);
    }


    return (
        <div className='duanzi'>
            <ul>
                {
                    duanzi.map(item => {
                        return (
                            <li onClick={showModel(item)} key={item.id}>
                                <h3>{item.name}</h3>
                                <p>{item.text.length > 90 ? item.text.slice(0,90)+"..." : item.text}</p>
                            </li>
                        )
                    })
                }
                
            </ul>

           {
               model ?  
               <>
                    {/* 模态框 */}
                    <div className='model'>
                        <h1 className='close' onClick={hide}> X </h1>
                        <h3>{one.name}</h3>
                        <p>{one.text}</p>
                    </div>
                    <div className='bg'></div>
               </> : null
           }



        </div>
    )
}
